package com.yc.navy.dayfresh.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.yc.navy.dayfresh.bean.TypeInfo;
import com.yc.navy.dayfresh.enums.ResultEnum;
import com.yc.navy.dayfresh.service.ITypeInfoService;
import com.yc.navy.dayfresh.util.ConstantInfo;
import com.yc.navy.dayfresh.vo.LayuiVO;
import com.yc.navy.dayfresh.vo.ResultVO;

/**
 * 视频类型控制层
 * @author acer
 *
 */
@RestController
@RequestMapping("/type")
public class TypeInfoController {
	@Autowired
	private ITypeInfoService typeInfoService;
	
	@PostMapping("/add")
	public ResultVO add(TypeInfo tf,MultipartFile photo) {//MultpartFile
		String savePath = "";
		File dest = null;
		
		if(photo != null && photo.getSize() >0) {
			try {
				savePath = ConstantInfo.UPLOADPATH + "/" + System.currentTimeMillis() + "_" + photo.getOriginalFilename();
				dest = new File(ConstantInfo.basepath,savePath);
				photo.transferTo(dest);
				tf.setPic(savePath);
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		int result = typeInfoService.add(tf);//添加，执行就就行，不用传去前端
		if(result == -1) {
			return new ResultVO(ResultEnum.CHECK_ERROR);
		}
		
		if(result >0) {
			return new ResultVO(ResultEnum.SUCCESS);
		}
		
		return new ResultVO(ResultEnum.ERROR);
	}
	
	@PostMapping("/list")
	public LayuiVO list(@RequestParam Map<String,Object> map) {
		map.forEach((key,val)->{
			System.out.println("["+key+":" + val + "]");
		});
		
		return typeInfoService.findByPageForBack(map);
	}
	
	@PostMapping("/update")
	public ResultVO update(TypeInfo tf) {
		int result = typeInfoService.update(tf);
		if(result >0) {
			return new ResultVO(ResultEnum.SUCCESS);
		}
		return new ResultVO(ResultEnum.ERROR);
	}
	
	@GetMapping("/finds")
	public ResultVO finds() {
		List<TypeInfo> list = typeInfoService.finds();
		if(list == null || list.isEmpty()) {
			return new ResultVO(ResultEnum.DATA_NULL);
		}
		return new ResultVO(ResultEnum.SUCCESS,list);
	}
}
